"""
Open API Client SDK
"""
import hmac
import json
from collections import OrderedDict
from hashlib import sha1

import requests

from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)


class SafeDogClient:
    def __init__(self, api_domain, app_key, app_secret, use_https=False):
        self.api_domain = api_domain
        self.app_key = app_key
        self.app_secret = app_secret
        self.http_domain = ('https://' if use_https else 'http://') + api_domain + '/'

    def verify_token(self, user_id, token, ip):
        data = {
            'app_key': self.app_key,
            'user_id': user_id,
            'token': token,
            'ip': ip
        }
        sorted_data = json.dumps(OrderedDict(sorted(data.items())))
        sign = self._encrypt_data(sorted_data)
        data['sign'] = sign

        return self._request('verify_token', data)

    def _request(self, uri, data):
        _LOGGER.info('request: {} - {}'.format(uri, data))
        resp = requests.post(self.http_domain + uri, data=data)
        _LOGGER.info('response text: {}'.format(resp.text))

        if resp.status_code != 200:
            return False
        resp_json = json.loads(resp.content)
        return resp_json['status'] == 0

    def _encrypt_data(self, data):
        return hmac.new(self.app_secret.encode(), data.encode('utf-8'), sha1).hexdigest()


client = SafeDogClient('103.230.241.52:8888', 'FJqTbpVC8rwqRMNEovJnihBZtrN2GOp8fJl6vl3P',
                       'dyhcy1Rlfg7YXQ5S8nwX71v7uwuT95tYLDcn7QnH')


def google_verify_token(user_id, g_code, ip):
    return client.verify_token(user_id, g_code, ip)
